﻿
Imports osi.root.connector
Imports osi.root.utils
Imports osi.root.formation
Imports utils = osi.root.utils

Partial Public Class device_manager
    Private Sub New()
    End Sub

    Private Shared ReadOnly m As unique_strong_map(Of String, idevice_pool)

    Shared Sub New()
        assert(DirectCast(Nothing, Boolean) = False)
        assert(DirectCast(Nothing, Object) Is Nothing)
        assert(DirectCast(Nothing, Int64) = 0)
        m = New unique_strong_map(Of String, idevice_pool)()
        application_lifetime.stopping_handle(AddressOf close)
    End Sub

    Public Shared Sub close()
        utils.foreach(AddressOf m.foreach,
                      Sub(ByRef name As String, ByRef x As idevice_pool)
                          assert(Not x Is Nothing)
                          x.close()
                      End Sub)
        GC.KeepAlive(m)
    End Sub

    Public Shared Function [get](ByVal key As String, ByRef o As idevice_pool) As Boolean
        If String.IsNullOrEmpty(key) Then
            Return False
        Else
            Return m.get(key, o)
        End If
    End Function

    Public Shared Function [get](Of T As idevice_pool)(ByVal key As String, ByRef o As T) As Boolean
        Dim d As idevice_pool = Nothing
        Return [get](key, d) AndAlso
               cast(Of T)(d, o)
    End Function

    Public Shared Function [erase](ByVal key As String,
                                   Optional ByRef o As idevice_pool = Nothing) As Boolean
        If String.IsNullOrEmpty(key) Then
            Return False
        Else
            Return m.erase(key, o)
        End If
    End Function

    Public Shared Function retire(ByVal key As String) As Boolean
        Dim o As idevice_pool = Nothing
        If [erase](key, o) Then
            o.close()
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function register(ByVal key As String, ByVal p As idevice_pool) As Boolean
        If String.IsNullOrEmpty(key) OrElse p Is Nothing Then
            Return False
        Else
            Return m.set(key, p)
        End If
    End Function
End Class
